import model from 'model'
import notiy from '../../components/notification/function'
import bus from '../../util/bus'
const handleError = (err) => {
  // handle error
  if (err.code === 401) {
    notiy({
      content: '您得先登录！'
    })
    bus.$emit('auth')
  }
}
export default {
  updateCountSync (store, data) {
    setTimeout(() => {
      store.commit('updateCount', data.num)
    }, 1000)
  },
  fetchTodos ({commit}) {
    return model.getAllTodos()
      .then(data => {
        commit('fillTodos', data)
      })
      .catch(err => {
        handleError(err)
      })
  },
  login ({commit}, {username, password}) {
    return new Promise((resolve, reject) => {
      model.login(username, password)
        .then(data => {
          commit('doLogin', data)
          notiy({
            content: '登陆成功'
          })
          resolve()
        })
        .catch(err => {
          handleError(err)
          reject(err)
        })
    })
  },
  addTodo ({commit}, todo) {
    model.createTodo(todo)
      .then(data => {
        commit('addTodo', data)
        notiy({
          content: '你又多了一件事要做'
        })
      }).catch(err => {
        handleError(err)
      })
  },
  updateTodo ({commit}, {id, todo}) {
    model.updateTodo(id, todo)
      .then(data => {
        commit('updateTodo', {id, todo: data})
      }).catch(err => {
        handleError(err)
      })
  },
  deleteTodo ({commit}, id) {
    model.deleteTodo(id)
      .then(data => {
        commit('deleteTodo', id)
        notiy({
          content: '你又shao了一件事要做'
        })
      }).catch(err => {
        handleError(err)
      })
  },
  deleteAllCompleted ({commit, state}) {
    const ids = state.todos.filter(t => t.completed).map(t => t.id)
    model.deleteAllcompleted(ids)
      .then(() => {
        commit('deleteAllcompleted')
        notiy({
          content: 'OK'
        })
      }).catch(err => {
        handleError(err)
      })
  }
}
